package com.example.swing;

import javax.swing.*;
import java.awt.*;

public class MatrixVisualizer extends JPanel {

    private final int[][] matrix;
    private final int cellSize = 50;

    public MatrixVisualizer(int[][] matrix) {
        this.matrix = matrix;
        int panelWidth = matrix[0].length * cellSize + 200;
        int panelHeight = matrix.length * cellSize + 200;
        setPreferredSize(new Dimension(panelWidth, panelHeight));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (matrix == null) return;

        Graphics2D g2 = (Graphics2D) g;

        int matrixWidth = matrix[0].length * cellSize;
        int matrixHeight = matrix.length * cellSize;

        // 计算中心偏移
        int xOffset = (getWidth() - matrixWidth) / 2;
        int yOffset = (getHeight() - matrixHeight) / 2;

        g2.translate(xOffset, yOffset);  // 设置起始绘制位置

        for (int row = 0; row < matrix.length; row++) {
            for (int col = 0; col < matrix[0].length; col++) {
                int val = matrix[row][col];

                // 背景颜色
                g2.setColor(Color.WHITE);
                g2.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);

                // 边框
                g2.setColor(Color.BLACK);
                g2.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);

                // 数字
                g2.setColor(Color.BLACK);
                g2.drawString(String.valueOf(val), col * cellSize + 20, row * cellSize + 30);
            }
        }

        g2.translate(-xOffset, -yOffset); // 恢复 transform（可选）
    }

    private Color getColorForValue(int val) {
        switch (val) {
            case 0:
                return new Color(220, 220, 220);
            case 1:
                return new Color(180, 220, 240);
            case 2:
                return new Color(255, 180, 100);
            case 3:
                return new Color(200, 200, 255);
            default:
                return new Color(180, 180, 180);
        }
    }

    /**
     * 静态方法：显示一个二维矩阵的可视化窗口
     */
    public static void show(int[][] matrix) {
        JFrame frame = new JFrame("Matrix Visualizer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MatrixVisualizer(matrix));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    // 示例 main 方法（可删除）
    public static void main(String[] args) {
        int[][] image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
        MatrixVisualizer.show(image);
    }
}

